package git.soulbgm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import git.soulbgm.common.base.BaseController;
import git.soulbgm.common.pojo.QueryDto;
import git.soulbgm.common.pojo.Response;
import git.soulbgm.pojo.DictData;
import git.soulbgm.service.DictDataService;
import git.soulbgm.utils.EasyPoiUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 字典数据控制器
 *
 * @author SoulBGM
 * @date 2022/03/25 17:14
 */
@RestController
@RequestMapping("system/dict/data")
public class DictDataController extends BaseController {

    private final DictDataService dictDataService;

    public DictDataController(DictDataService dictDataService) {
        this.dictDataService = dictDataService;
    }

    @PostMapping("list")
    public Response list(@RequestBody QueryDto<DictData> dto, Page<DictData> queryPage) {
        Page<DictData> resultPage = dictDataService.page(queryPage, new QueryWrapper<>(dto.getData()));
        return success(resultPage);
    }

    @GetMapping("export")
    public void export(DictData info, HttpServletResponse response) {
        List<DictData> list = dictDataService.list(new QueryWrapper<>(info));
        try {
            EasyPoiUtil.exportExcel(response, "服务数据", list, DictData.class);
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }

    @PostMapping("add")
    public Response add(DictData info) {
        boolean result = dictDataService.save(info);
        dictDataService.refreshCache();
        return result ? success() : error();
    }

    @PostMapping("remove")
    public Response remove(String ids) {
        boolean result = dictDataService.removeByIds(Arrays.asList(ids.split(",")));
        dictDataService.refreshCache();
        return result ? success() : error();
    }

    @PostMapping({"changeStatus", "edit"})
    public Response edit(DictData info) {
        boolean result = dictDataService.updateById(info);
        dictDataService.refreshCache();
        return result ? success() : error();
    }

    @GetMapping("getType")
    public Response getType(String dictType) {
        return success(dictDataService.getType(dictType));
    }
}
